﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Web.Mvc;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Net.Mail;
using System.Web.Helpers;
using vITs.Site.Models.DataModels;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace vITs.Site.Models
{
    public static class Utilities
    {
        public static String GeneratePasswordHash(String password)
        {
            const string salt = "E7[+yE^O*wZ!%5Wr";
            byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

            Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(password, saltBytes, 8096);
            byte[] hashedBytes = db.GetBytes(128);
            StringBuilder sb = new StringBuilder();

            foreach (byte b in hashedBytes) sb.Append(b.ToString("X2"));

            return sb.ToString();
        }

        public static string BaseSiteUrl
        {
            get
            {
                HttpContext context = HttpContext.Current;
                string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
                return baseUrl;
            }
        }

        public static bool TrySendMail(User receiver, String subject, String body, out string error)
        {
            error = String.Empty;

            WebMail.SmtpServer = "smtp.gmail.com";
            WebMail.SmtpPort = 587;
            WebMail.EnableSsl = true;
            WebMail.UserName = "oru.vits@gmail.com";
            WebMail.Password = "foobar123";
            WebMail.From = "noreply@vits.tld";

            try
            {
                WebMail.Send(receiver.EmailAddress, subject, body);
            }
            catch (Exception e)
            {
                error = e.Message;
                return false;
            }

            return true;
        }

        public static SelectList ToSelectList<T>(this T enumObj) where T : struct, IConvertible
        {
            Type t = typeof(T);
            if (!t.IsEnum) throw new ArgumentException("enumObj has to be an Enum");

            var values = Enum.GetValues(t).Cast<Enum>().Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDisplayName() });

            return new SelectList(values, "Id", "Name", enumObj);
        }

        public static string GetDisplayName<T>(this T value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            if (fi != null)
            {
                DisplayAttribute[] ds = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);

                if (ds.Length == 1)
                {
                    return ds[0].Name;
                }
            }

            return value.ToString();
        }

        public static string ToSentenceCasing(this string text)
        {
            text = text.ToLower();
            int capturePosition;
            Capture capture;
            char[] messageArray = text.ToCharArray();

            const string pattern = @"[^\s]\.[\s\\n\\r]+[a-z]";
            var ms = Regex.Matches(text, pattern);
            for (int i = 0; i < ms.Count; i++)
            {
                capture = ms[i].Captures[0];
                capturePosition = capture.Index + capture.Value.Length - 1;
                messageArray[capturePosition] = char.ToUpper(messageArray[capturePosition]);
            }
            ms = Regex.Matches(text, @"^[\s\\r\\n]*[a-z]");
            if (ms.Count > 0)
            {
                capture = ms[0].Captures[0];
                capturePosition = capture.Index + capture.Value.Length - 1;
                messageArray[capturePosition] = char.ToUpper(messageArray[capturePosition]);
            }
            return new string(messageArray);
        }

        public static string[,] CreateExcelBase(List<Assignment> LOA)
        {
            string[,] ExcelBase = new string[LOA.Count + 1, 15];
            int i;

            ExcelBase[0, 0] = "Uppdragsnamn";
            ExcelBase[0, 1] = "Startdatum";
            ExcelBase[0, 2] = "Slutdatum";
            ExcelBase[0, 3] = "Konsultens namn";
            ExcelBase[0, 4] = "Handläggarens namn";
            ExcelBase[0, 5] = "Uppdragets totala kostnad";

            for (i = 0; i < LOA.Count; i++)
            {
                int j = i + 1;
                ExcelBase[j, 0] = LOA[i].AssignmentName;
                ExcelBase[j, 1] = LOA[i].StartDate.ToString();
                ExcelBase[j, 2] = LOA[i].EndDate.ToString();
                ExcelBase[j, 3] = LOA[i].Consultant.GetFullName();
                ExcelBase[j, 4] = LOA[i].Handler.GetFullName();
                ExcelBase[j, 5] = LOA[i].GetTotalCost().ToString();
            }

            return ExcelBase;
        }

        public static int[] GetValidYears()
        {
            int[] retval = new int[2500 - 1900];

            for (int i = 0; i < retval.Length; i++)
            {
                retval[i] = i + 1900;
            }

            return retval;
        }
    }
}